package com.zfy.dao;

import com.zfy.entity.Product;
import com.zfy.utils.DBManager;
import com.zfy.utils.QueryDataResult;

import java.util.ArrayList;
import java.util.List;

public class ProductDao {

    public List<Product> getProduct(Integer page, Integer limit,String pname,Double min,Double max,Integer cid){
        String sql = " SELECT p.*,c.cnameFROM product p,category c WHERE p.cid=c.cid ";
        if( pname != null && !pname.equals("")){
            sql += " AND pname LIKE '%"+pname+"%' ";
        }
        if( min == null && max !=null && !max.equals("") ){
            sql += " AND pprice <= "+max+" ";
        }
        if (max == null && min != null && !min.equals("")) {
            sql += " AND pprice >= "+min+" ";
        }
        if(min != null && !min.equals("") && max !=null && !max.equals("") ){
            sql += " AND pprice BETWEEN "+min+" AND "+max+" ";
        }
        if ( cid != null && !cid.equals("")){
            sql += " AND p.cid = "+cid+" ";
        }
        if( page !=null && limit !=null ) {
            sql += " LIMIT "+(page-1)*limit+","+limit;
        }
        QueryDataResult qr = DBManager.executeQuery(sql);
        List<Product> productList = new ArrayList<Product>();
        if( qr != null) {
            try{
                while (qr.rs.next()){
                    Product product = new Product();
                    product.setPid(qr.rs.getInt("pid"));
                    product.setPname(qr.rs.getString("pname"));
                    product.setPprice(qr.rs.getDouble("pprice"));
                    product.setPstate(qr.rs.getInt("pstate"));
                    product.setPstock(qr.rs.getInt("pstock"));
                    product.setPimg(qr.rs.getString("pimg"));
                    product.setPintro(qr.rs.getString("pintro"));
                    product.setCname(qr.rs.getString("cname"));
                    product.setCid(qr.rs.getInt("cid"));
                    productList.add(product);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return productList;
    }
}
